<script setup>
import { Modal } from 'ant-design-vue'
import { ColumnHeightOutlined, DownOutlined, PlusOutlined, ReloadOutlined, SettingOutlined, UpOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import { getQueryParam } from '~/utils/tools'
import { getExcuteList, getLog, getLogTask } from '~@/api/task/index'

defineOptions({
  name: 'Log',
})
const formRef = ref()
const excuteOptions = shallowRef([])// 执行器
const taskOptions = shallowRef([])// 任务
// 调度时间
const rangePresets = ref([
  {
    label: '今日',
    value: [dayjs(), dayjs()],
  },
  {
    label: '昨日',
    value: [dayjs().subtract(1, 'day'), dayjs().subtract(1, 'day')],
  },
  {
    label: '本月',
    value: [dayjs().startOf('month'), dayjs().endOf('month')],
  },
  {
    label: '上个月',
    value: [
      dayjs().subtract(1, 'month').startOf('month'),
      dayjs().subtract(1, 'month').endOf('month'),
    ],
  },
  {
    label: '最近一周',
    value: [dayjs().add(-7, 'd'), dayjs()],
  },
  {
    label: '最近一月',
    value: [dayjs().add(-30, 'd'), dayjs()],
  },
])
const labelCol = {
  span: 6,
}
const wrapperCol = {
  span: 14,
}
const formState = reactive({
  userId: '',
  userName: '',
  gender: '',
  email: '',
  phone: '',
  address: '',
  certNo: '',
})
const rules = {
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
}

const statusMap = {
  0: '关闭',
  1: '运行中',
  2: '上线',
  3: '错误',
}
const message = useMessage()
const columns = shallowRef([
  {
    title: '任务ID',
    dataIndex: 'jobId',
    width: 80,
  },
  {
    title: '调度时间',
    dataIndex: 'triggerTime',
    width: 200,
  },
  {
    title: '调度备注',
    dataIndex: 'triggerMsg',
    width: 200,
  },

  {
    title: '调度结果',
    dataIndex: 'triggerCode',
    width: 150,
  },
  {
    title: '执行备注',
    dataIndex: 'handleMsg',
    width: 200,
  },

  {
    title: '执行时间',
    dataIndex: 'handleTime',
    width: 200,
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '--'
      }
    },

  },
  {
    title: '执行结果',
    dataIndex: 'handleCode',
    width: 150,
  },
  // {
  //   title: '执行备注',
  //   dataIndex: 'handleMsg',
  //   width: 180,
  // },
])
const statusOptions = shallowRef([
  { configKey: -1, configValue: '全部' },
  { configKey: 1, configValue: '成功' },
  { configKey: 2, configValue: '失败' },
  { configKey: 3, configValue: '进行中' },
])
const loading = shallowRef(false)
const totalNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const formModel = reactive({
  jobGroup: void 0,
  jobId: void 0,
  logStatus: void 0,
  filterTime: void 0,
  filterTimeStart: void 0,
  filterTimeEnd: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)
const editOpen = ref(false)
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
onMounted(() => {
  getExcute()
  formModel.logStatus = statusOptions.value[0].configKey
  const jobGroup = getQueryParam('jobGroup')
  const jobId = getQueryParam('jobId')
  if (jobId) {
    formModel.jobId = Number(jobId)
  }
  if (jobGroup) {
    formModel.jobGroup = Number(jobGroup)
  }
  else {
    init()
  }
})
// 获取执行器列表
async function getExcute() {
  try {
    const res = await getExcuteList()
    // window.location.href='https://heren-pay-reconciliation.cn-hangzhou.oss.aliyuncs.com/test/card/bill/CARD_RECHARGE20250307.xls'
    excuteOptions.value = res.data
    if (formModel.jobGroup) {
      getTask(formModel.jobGroup)
    }
  }
  catch (e) {
  }
  finally {
    console.log(22)
  }
}
// 获取任务列表
async function getTask(value) {
  try {
    const res = await getLogTask(value)
    // window.location.href='https://heren-pay-reconciliation.cn-hangzhou.oss.aliyuncs.com/test/card/bill/CARD_RECHARGE20250307.xls'
    taskOptions.value = res.data
    init()
  }
  catch (e) {
  }
  finally {
    console.log(22)
  }
}
function handleSelectChange(value) {
  getTask(value)
}

// 搜索
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const filterTimeStart = formModel.filterTime?.[0]?.format('YYYY-MM-DD')
    const filterTimeEnd = formModel.filterTime?.[1]?.format('YYYY-MM-DD')
    const { data } = await getLog({
      param: { ...formModel, filterTimeStart, filterTimeEnd },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    // dataSource.value = data.data ?? []
    totalNum.value = data.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 更新用户信息
async function onSubmit() {
  try {
    await formRef.value.validate()
    const { data } = await updateUser(formState)
    message.success('保存成功')
    init()
    open.value = false
  }
  catch (error) {
    // message.error('请检查表单填写是否正确')
  }
}
function resetForm() {
  formRef.value.resetFields()
}
// 返回
function handleReturn() {
  editOpen.value = false
}
async function onSearch() {
  pagination.current = 1
  await init()
}
// 重置查询参数
async function onReset() {
  formModel.filterTimeEnd = void 0
  formModel.filterTimeStart = void 0
  formModel.logStatus = void 0
  formModel.jobGroup = void 0
  formModel.jobId = void 0
  formModel.filterTime = void 0
  await init()
}

// 编辑
async function handleEdit(record) {
  open.value = true
  formState.userId = record.userId
  formState.userName = record.userName
  formState.gender = record.gender
  formState.email = record.email
  formState.address = record.address
  formState.certNo = record.certNo
  formState.phone = record.phone
}

function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
function handleCheckAllChange(e) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}
watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)
// 处理证件号
function handleCertcard(certNo) {
  if (!certNo)
    return ''
  const len = certNo.length
  if (len <= 4)
    return certNo // 短于4位不处理
  return certNo.slice(0, 3) + '*'.repeat(len - 7) + certNo.slice(-4)
}
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}
function handleCheckChange(value) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}
const expand = ref(false)
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 7 }" :model="formModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="8">
            <a-form-item name="jobGroup" label="执行器">
              <a-select v-model:value="formModel.jobGroup" placeholder="请选择" allow-clear @change="handleSelectChange">
                <a-select-option v-for="item in excuteOptions" :key="item.id" :value="item.id">
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="任务">
              <a-select v-model:value="formModel.jobId" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in taskOptions" :key="item.id" :value="item.id">
                  {{ item.jobDesc }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="状态">
              <a-select v-model:value="formModel.logStatus" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in statusOptions" :key="item.configKey" :value="item.configKey">
                  {{ item.configValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="调度时间">
              <a-range-picker v-model:value="formModel.filterTime" style="width:100%" :presets="rangePresets" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :span="24" style="text-align: right;" class="ml-10">
          <a-col :span="24">
            <a-space flex justify-end w-full>
              <a-button type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card>
      <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'triggerCode'">
            <span :style="{ color: record.triggerCode === 200 ? '#389e0d' : '#f5222d' }">{{ record.triggerCode === 200 ? '成功' : '失败' }}</span>
          </template>
          <!-- 调度备注 -->
          <template v-else-if="column.dataIndex === 'triggerMsg'">
            <span v-if="record.triggerMsg === null || record.triggerMsg === ''">无</span>
            <div v-else>
              <a-popover title="调度备注">
                <template #content>
                  <div v-html="record.triggerMsg" />
                </template>
                <a-button type="link" style="color:#3c8dbc">
                  查看
                </a-button>
              </a-popover>
            </div>
          </template>
          <!-- 执行备注 -->
          <template v-else-if="column.dataIndex === 'handleMsg'">
            <span v-if="record.handleMsg === null || record.handleMsg === ''">无</span>
            <div v-else>
              <a-popover title="执行备注">
                <template #content>
                  <div v-html="record.handleMsg" />
                </template>
                <a-button type="link" style="color:#3c8dbc">
                  查看
                </a-button>
              </a-popover>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'handleCode'">
            <span :style="{ color: record.handleCode === 200 ? '#389e0d' : '#f5222d' }">{{ record.handleCode === 200 ? '成功' : '失败' }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <div class="resetPass flex flex-center">
              <a @click="handleEdit(record)">编辑</a>
              <a v-if="record.status === 'ACTIVE'" @click="handleFreeze(record)">冻结账户</a>
              <a v-if="record.status === 'MANUAL_FREEZE'" @click="handleUnfreeze(record)">解冻账户</a>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
  </page-container>
</template>

    <style lang="less" scoped>
      .resetPass{
        a{
          margin-right: 10px;
        }
      }
      .red{
        color:red;
        /* color:#ff4d4f; */
      }
      .card-title{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        flex: auto;
        color: rgba(0, 0, 0, 0.88);
        font-weight: 600;
        font-size: 16px;
        line-height: 1.5;
      }
    @media screen and (max-width: 1200px) and (min-width: 992px) {
      .activeCard {
        margin-bottom: 24px;
      }
      .members {
        margin-bottom: 0;
      }
      .extraContent {
        margin-left: -44px;
        .statItem {
          padding: 0 16px;
        }
      }
    }

    @media screen and (max-width: 992px) {
      .activeCard {
        margin-bottom: 24px;
      }
      .members {
        margin-bottom: 0;
      }
      .extraContent {
        float: none;
        margin-right: 0;
        .statItem {
          padding: 0 16px;
          text-align: left;
          &::after {
            display: none;
          }
        }
      }
    }

    @media screen and (max-width: 768px) {
      .extraContent {
        margin-left: -16px;
      }
      .projectList {
        .projectGrid {
          width: 50%;
        }
      }
    }

    @media screen and (max-width: 576px) {
      .pageHeaderContent {
        display: block;
        .content {
          margin-left: 0;
        }
      }
      .extraContent {
        .statItem {
          float: none;
        }
      }
    }

    @media screen and (max-width: 480px) {
      .projectList {
        .projectGrid {
          width: 100%;
        }
      }
    }
    </style>
